import React from 'react';
import { Table, Icon, Button, Row, Col, Modal } from 'antd';
import { WeaInput, WeaTextarea, WeaSelect, WeaBrowser, WeaDatePicker, WeaTimePicker, WeaCheckbox, WeaDragula } from 'ecCom';
import { observer } from 'mobx-react';
import jQuery from "jquery";
import {writeLog} from "../../util/modeUtil";
//国际化 zxt- 20170419
const defaultLocale = {
    total: '共',
    totalUnit: '条',
};

export interface TableEditProps {
    locale?: any;
    datas: any[];
    columns: any[];
    addFirstRow?: boolean;
    selectedRowKeys?: string[];
    tableProps?: any;
    draggable?: boolean;
    title?: string;
    viewAttr?: number;
    showAdd?: boolean;
    showCopy?: boolean;
    showDelete?: boolean;
    pageSize?: number;
    paginationSize?: string;
    onRowSelect?: Function;
    getRowSelection?: Function;
    addPosition?:string;
    deleteConfirm?:boolean;
    
    rowKey:Function | string;
    onChange?:Function;
}
@observer
class Main extends React.Component<TableEditProps, any> {
    getLocale = () => {
        let locale = {};
        if (this.context.antLocale && this.context.antLocale.Table) {
            locale = this.context.antLocale.WeaTableEdit;
        }
        return {
            ...defaultLocale,
            ...locale,
            ...this.props.locale
        };
    }
    constructor(props: TableEditProps) {
        super(props);
        this.state = {
            columns: [],
            datas: [],
            selectedRowKeys: [],
            current: 1
        }
        this.onEdit = this.onEdit.bind(this);
        this.doCopy = this.doCopy.bind(this);
        this.doDelete = this.doDelete.bind(this);
        this.doAdd = this.doAdd.bind(this);
    }
    componentDidMount() {
        let { datas = [], columns = [], addFirstRow = false } = this.props;
        if (addFirstRow && datas.length == 0) {
            datas = [{}];
        }
        columns.length > 0 && this.setState(datas.length > 0 ? { datas: this.addKeytoDatas(datas), columns } : { datas: [], columns });
    }
    
    componentDidUpdate() {

    }
    addKeytoDatas = (datas) => {
        let _datas = datas.map((data, i) => {
            let _data = { ...data };
            _data.key = i
            return _data
        })
        return _datas
    }
    render() {
        const { datas } = this.state;
        //rc-table 的底层 title 有问题，直接这里搞个吧
        let renderContent = (
            <div className="wea-table-edit" >
                {this.getTitle()}
                <Table
                    {...this.props.tableProps}
                    columns={this.getColumns()}
                    dataSource={datas}
                    pagination={this.getPagination()}
                    rowSelection={this.getRowSelection()}
                    ref="table"
                />
            </div>
        );
        if (this.props.draggable) {
            return (
                <WeaDragula container=".ant-table-tbody"
                    canDrag={this.canDrag}
                    datas={datas}
                    getKeyFromData={this.getRowKey}
                    getKeyFromDom={this.getKeyFromDom}
                    onDrop={this.onDrop}>
                    {renderContent}
                </WeaDragula>
            );
        } else {
            return renderContent;
        }
    }
    canDrag = (clickDom) => jQuery(clickDom).hasClass("icon-coms-move")
    getTitle = () => {
        const { title = '', viewAttr = 2, showAdd = true, showDelete = true, showCopy = true } = this.props;
        const { columns, selectedRowKeys } = this.state;
        let readOnly = viewAttr === 1
        return (
            <Row className="wea-table-edit-title" >
                <Col>
                    {title}
                    <Button style={{ display: readOnly || !showCopy ? 'none' : 'block' }} className="copy" type="primary" disabled={readOnly || !`${selectedRowKeys}`} {...{ title: '复制' }} size="small" onClick={this.doCopy} ><span className="icon-coms-copy-hot" /></Button>
                    <Button style={{ display: readOnly || !showDelete ? 'none' : 'block' }} className="minus" type="primary" disabled={readOnly || !`${selectedRowKeys}`} {...{ title: '删除' }} size="small" onClick={this.doDelete} ><Icon type="minus" /></Button>
                    <Button style={{ display: readOnly || !showAdd ? 'none' : 'block' }} className="add" type="primary" disabled={readOnly || !`${columns}`}  {...{ title: '新增' }} size="small" onClick={this.doAdd}><Icon type="plus" /></Button>
                </Col>
            </Row>
        )
    }
    getColumns = () => {
        const { columns } = this.props;
        let _columns = ([] as any[]).concat(columns);
        _columns = _columns.map(col => {
            let _col = { ...col };
            _col.render || (_col.render = (text, record, index) => {
                return this.getColRender(_col, text, record, index);
            })
            return _col
        });
        if (this.props.draggable) {
            _columns = [{
                key: "drag",
                dataIndex: 'drag',
                render: (_, record, index) => {
                    return <span data-index={this.getRowKey(record, index)} key={this.getRowKey(record, index)} className="icon-coms-move cursor-pointer" />
                }
            }].concat(_columns);
        }
        return _columns
    }
    getColRender = (_col: any, _: string, record: any, index: number) => {
        const { com } = _col;
        let _com = [] as any[];
        com.map(c => {
            if (typeof c.props === 'object') {
                _com.push(c);
            } else {
                const { key, label = '', type = 'INPUT', options = [], browserConditionParam = {}, innerStyle = { width: "100%" },
                    viewAttr = 2, showTime = false, format = "yyyy-MM-dd", otherParams } = c;
                const _type = type.toUpperCase();
                let style = _type === 'BROWSER' ? { ...innerStyle } : { ...innerStyle, display: 'inline-block' }
                _com.push(
                    <span >
                        {label && <span style={{ marginLeft: 5 }}>{label}</span>}
                        {_type === 'INPUT' &&
                            <WeaInput
                                {...otherParams}
                                defaultValue={record[key]}
                                value={record[key]}
                                style={style}
                                viewAttr={viewAttr}
                                onBlur={value => this.onEdit(record, index, key, value)} />
                        }
                        {_type === 'TEXTAREA' &&
                            <WeaTextarea
                                {...otherParams}
                                defaultValue={record[key]}
                                value={record[key]}
                                style={style}
                                viewAttr={viewAttr}
                                onBlur={value => this.onEdit(record, index, key, value)} />
                        }
                        {_type === 'DATEPICKER' &&
                            <WeaDatePicker
                                {...otherParams}
                                showTime={showTime}
                                format={format}
                                defaultValue={record[key]}
                                value={record[key]}
                                style={style}
                                viewAttr={viewAttr}
                                onChange={value => this.onEdit(record, index, key, value)} />
                        }
                        {_type === 'TIMEPICKER' &&
                            <WeaTimePicker
                                {...otherParams}
                                defaultValue={record[key]}
                                value={record[key]}
                                style={style}
                                viewAttr={viewAttr}
                                onChange={value => this.onEdit(record, index, key, value)} />
                        }
                        {_type === 'SELECT' &&
                            <WeaSelect
                                {...otherParams}
                                defaultValue={record[key]}
                                value={record[key]}
                                options={options}
                                style={style}
                                viewAttr={viewAttr}
                                onChange={value => this.onEdit(record, index, key, value)} />
                        }
                        {_type === 'BROWSER' &&
                            <WeaBrowser
                                layout={document.body}
                                {...otherParams}
                                replaceDatas={this.getBrowerDatas(record, key)}
                                {...browserConditionParam}
                                inputStyle={style}
                                viewAttr={viewAttr}
                                onChange={(ids, names, bDatas) => this.onEdit(record, index, key, ids, names, bDatas)} />
                        }
                        {_type === 'CHECKBOX' &&
                            <WeaCheckbox
                                {...otherParams}
                                style={style}
                                value={record[key]}
                                viewAttr={viewAttr}
                                onChange={(value) => this.onEdit(record, index, key, value)}
                            />
                        }
                    </span>
                )
            }
        });
        return (
            <div>
                {_com}
            </div>
        )
    }
    getBrowerDatas = (record, key) => {
        let replaceDatas = [] as any[];
        if (record[key + 'span'] !== undefined) {
            let keys = record[key].split(',');
            let values = record[key + 'span'].split(',');
            if (keys.length === values.length) {
                keys.map((k, i) => {
                    if (k != '' && values[i] != '') replaceDatas.push({ id: k, name: values[i] });
                });
            } else {
                writeLog('浏览按钮数据有误！！，显示名中不能包含有英文逗号" , "','');
            }
        }
        return replaceDatas
    }
    getPagination = () => {
        const { pageSize = 0, paginationSize = '' } = this.props;
        if (!pageSize) return false;
        const { current } = this.state;
        let obj = {
            size: paginationSize,
            current,
            pageSize,
        };
        return obj
    }
    getRowSelection = () => {
        const { columns, selectedRowKeys } = this.state;
        if (!`${columns}`) return null
        let rowSelection = {
            selectedRowKeys,
            onChange: (sRowKeys: any, _: any) => {
                this.setState({ selectedRowKeys: sRowKeys });
                typeof this.props.onRowSelect === 'function' && this.props.onRowSelect(sRowKeys);
            }
        }
        if (this.props.getRowSelection) {
            return this.props.getRowSelection(rowSelection);
        } else {
            return rowSelection
        }
    }
    onEdit = (_: any, index: number, key: string, value: any, names?: any, __?: any) => {
        const { pageSize = 0 } = this.props;
        const { datas, current } = this.state;
        let _datas = [].concat(datas);
        _datas[pageSize * (current - 1) + index][key] = value;
        if (names) _datas[pageSize * (current - 1) + index][key + 'span'] = names;
        this.setState({ datas: _datas });
        this.onChange(_datas);
    }
    doCopy = () => {
        const { datas, selectedRowKeys } = this.state;
        let _datas = ([] as any[]).concat(datas);
        selectedRowKeys.map(key => {
            datas.map(data => {
                if (data.key == key) {
                    let _data = { ...data };
                    _data.key = _datas.length;
                    _datas.push(_data)
                }
            })
        });
        this.setState({ datas: _datas });
        this.onChange(_datas);
    }
    doAdd = ()=> {
        let { datas, selectedRowKeys } = this.state;
        let _data = { ...datas[0] };
        for (let k in _data) {
            _data[k] = ''
        }
        let _datas;
        if (this.props.addPosition == "first") {
            _datas = [_data].concat(datas);
            _datas.forEach((data, index) => {
                data.key = index;
            });
            selectedRowKeys = selectedRowKeys.map((i) => i + 1);
            this.setState({ datas: _datas, selectedRowKeys });
        } else {
            _datas = [].concat(datas);
            _data.key = _datas.length;
            _datas.push(_data);
            this.setState({ datas: _datas });
        }
        this.onChange(_datas);
    }
    doDelete = ()=> {
        let { deleteConfirm } = this.props;
        let delOper = () => {
            const { datas, selectedRowKeys } = this.state;
            let _datas = ([] as any[]).concat(datas);
            selectedRowKeys.map(key => {
                _datas = _datas.filter(data => data.key !== key)
            });
            _datas = _datas.map((data, i) => {
                let _data = { ...data };
                _data.key = i;
                return _data
            })
            this.setState({ datas: _datas, selectedRowKeys: [] });
            this.onChange(_datas);
        };
        if (deleteConfirm) {
            Modal.confirm({
                title: "系统提示",
                content: "确认要删除吗？",
                onOk: delOper
            });
        } else {
            delOper();
        }

    }
    onChange = (datas:any[]) => {
        const { columns } = this.state;
        let _datas = datas.map((data) => {
            let _data = { ...data }
            delete _data.key
            return _data
        })
        typeof this.props.onChange === 'function' && this.props.onChange(_datas, columns);
    }
    getKeyFromDom = (dom:any) => {
        return jQuery("span.icon-coms-move", dom).attr("data-index");
    }
    onDrop = (datas:any[]) => {
        this.setState({ datas: datas }, () => this.onChange(this.state.datas));
    }

    getRowKey = (record:any, index:number) => {
        const rowKey = this.props.rowKey;
        if (typeof rowKey === 'function') {
            return rowKey(record, index);
        }
        return typeof record[rowKey] !== 'undefined' ? record[rowKey] : (record.id || index);
    }

    setDatas = (datas:any[]) => {
        this.setState({
            datas: this.addKeytoDatas(datas)
        });
    }
}

export default Main;

//let columns_mock = [
//	{
//		title: '测试 mock1',
//		dataIndex: 'mock1',
//		key: 'mock1',
//		com: [
//			<span>直接传入组件</span>
//		],
//		colSpan: 1,
//		width: '20%',
//		className: 'test-mock1',
//	},
//	{
//		title: '测试 mock2',
//		dataIndex: 'mock2',
//		key: 'mock2',
//		com: [
//			{ label: '', type: 'BROWSER' , editType: '1', key: 'browser', browserConditionParam: {}, width: 120, },
//		],
//		colSpan: 1,
//		width: '20%',
//		className: 'test-mock2',
//	},
//	{
//		title: '测试 mock',
//		dataIndex: 'mock',
//		key: 'mock',
//		com: [
//			{ label: '', type: 'SELECT' ,editType: '1', key: 'fieldtype', options: [{ key: '0', showname: '单行文本框'},{ key: '1', showname:'多行文本框'}], width: 120, disabled: false, },
//			{ label: '类型：', type: 'SELECT' ,editType: '1', key: 'type', options: [{ key: '0', showname: '文本'}], width: 120, },
//			{ label: '文本长度：', type: 'INPUT' ,editType: '1', key: 'fieldlength', width: 120, },
//		],
//		colSpan: 1,
//		width: '60%',
//		className: 'test-mock',
//	},
//];

//let datas_mock = [
//	{
//		key: 0,
//		fieldtype: '0',
//		type: '0',
//		fieldlength: 200,
//      browserspan:'w1'
//      browser:'3'
//	}
//];